﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

//buddy
using Zeta;
using Zeta.Common;
using Zeta.CommonBot;
using Zeta.Common.Plugins;
using Zeta.Internals;
using Zeta.Internals.Actors;
using Zeta.Internals.Service;

namespace MyBuddy.Local
{
    internal class DBFileMonitor
    {
        private static int instanceCount = 0;
        public static DBFileMonitor GLOBAL = new DBFileMonitor();
        private bool locked = false;
        private const string fileName = "\\whereIsMyBuddy.xml";

        public DBFileMonitor()
        {
            if (instanceCount >= 1)
            {
                throw new Exception("Max instances reached.");
            }

            instanceCount += 1;
        }

        public void UpdateLeaderLocation()
        {
            if (null == ZetaDia.Me) return;
            if (locked) return;
            

            locked = true; //this only works with one leader plugin

            lock (this)
            {
                string fp = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fileName;
                if (File.Exists(fp))
                {
                    try { File.Delete(fp); }
                    catch (Exception ex) { Logging.Write(LogLevel.Verbose, "Leader failed to delete file: " + ex.Message); }
                }

                FileStream fs = null;
                XmlTextWriter xw = null;

                try
                {
                    fs = File.Open(fp, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                    if (null != fs)
                    {
                        try
                        {
                            xw = new XmlTextWriter(fs, Encoding.Default);
                            xw.WriteStartDocument();
                            xw.WriteStartElement("Profile");
                            xw.WriteStartElement("MoveTo");
                            xw.WriteAttributeString("questId", "1");
                            xw.WriteAttributeString("world", ZetaDia.Me.WorldDynamicId.ToString());
                            xw.WriteAttributeString("x", ZetaDia.Me.Position.X.ToString());
                            xw.WriteAttributeString("y", ZetaDia.Me.Position.Y.ToString());
                            xw.WriteAttributeString("z", ZetaDia.Me.Position.Z.ToString());
                            xw.WriteEndElement();
                            xw.WriteEndElement();
                            xw.WriteEndDocument();
                            xw.Close();
                            xw = null;
                            fs.Close();
                            fs = null;
                        }
                        catch (Exception exFileWriter)
                        { Logging.Write(LogLevel.Verbose, "Leader failed to write to file: " + exFileWriter.Message); }
                    }
                }
                catch (Exception exFile)
                { Logging.Write(LogLevel.Verbose, "Leader failed to open file: " + exFile.Message); }
                finally
                {
                    if (null != xw)
                    {
                        xw.Close();
                        xw = null;
                    }
                    if (null != fs)
                    {
                        fs.Close();
                        fs = null;
                    }
                }

            }

            locked = false;
        }

        public void FollowLeader()
        {
            if (null == ZetaDia.Me) return;

            if (locked) return;

            locked = true;

            FileStream fs = null;
            StreamReader sr = null;
            Vector3 moveTo = ZetaDia.Me.Position;
            string world = "";

            try { Zeta.CommonBot.LootTargeting.Instance.Pulse(); }
            catch (Exception exLooter) { Logging.Write(LogLevel.Verbose, "BuddyAutoFollower: " + exLooter.Message); }

            lock(this)
            {
                string fp = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + fileName;
                try
                {
                    if (File.Exists(fp))
                    {
                        Logging.Write("Opening file.");
                        fs = File.Open(fp, FileMode.Open, FileAccess.Read, FileShare.Read);
                        try
                        {
                            string xml = "";

                            sr = new StreamReader(fs);
                            xml = sr.ReadToEnd();
                            //Logging.Write(xml);

                            sr.Close();
                            sr.Dispose();
                            sr = null;
                            fs.Close();
                            fs = null;

                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(xml);

                            XmlNode n = doc.FirstChild;
                            if (n.Name != "Profile")
                                n = n.NextSibling;

                            //Logging.Write(n.Name);

                            if (null != n && n.ChildNodes.Count == 1)
                            {
                                if (n.ChildNodes[0].Name == "MoveTo")
                                {
                                    string x = n.ChildNodes[0].Attributes["x"].Value;
                                    string y = n.ChildNodes[0].Attributes["y"].Value;
                                    string z = n.ChildNodes[0].Attributes["z"].Value;

                                    world = n.ChildNodes[0].Attributes["world"].Value;
                                    Random r = new Random();
                                    Vector3 vary = new Vector3(r.Next(-1, 1), r.Next(-1, 1), r.Next(-1, 1));
                                    moveTo = new Vector3(float.Parse(x), float.Parse(y), float.Parse(z));
                                    moveTo += vary;
                                }
                            }
                        }
                        catch (Exception ex) { Logging.Write("Follower failed to parse file: " + ex.Message); }
                    }

                }
                catch (Exception ex) { Logging.Write(LogLevel.Verbose, "Follower failed to read file: " + ex.Message); }
                finally
                {
                    if (null != sr)
                    {
                        sr.Close();
                        sr.Dispose();
                        sr = null;
                    }

                    if (null != fs)
                    {
                        fs.Close();
                        fs = null;
                    }
                }
            }//lock

            locked = false;
            Logging.Write("Casting MOVE TO:" + moveTo.ToString());

            if ((ZetaDia.Me.Position.Distance(moveTo) >= 8) && ZetaDia.Me.Position != moveTo && ZetaDia.Me.WorldDynamicId.ToString() == world)
                ZetaDia.Me.UsePower(SNOPower.Walk, moveTo, ZetaDia.Me.WorldDynamicId, -1);

            try { Zeta.CommonBot.CombatTargeting.Instance.Pulse(); }
            catch (Exception exFight) { Logging.Write(LogLevel.Verbose, "BuddyAutoFollower: " + exFight.Message); }
        }

        //void MoveTo(Vector3 v)
        //{
        //    float x = ZetaDia.Me.Position.X;
        //    float y = ZetaDia.Me.Position.Y;
        //    float z = ZetaDia.Me.Position.Z;

        //    while (ZetaDia.Me.Position.Distance(v) > 3)
        //    {
        //        if (x > v.X) x -= 0.5f; else x += 0.5f;
        //        if (y > v.Y) x -= 0.5f; else y += 0.5f;
        //        if (z > v.Z) x -= 0.5f; else z += 0.5f; 
        //        ZetaDia.Me.UsePower(SNOPower.Walk, v, ZetaDia.Me.WorldDynamicId, 2, -1);
        //        System.Threading.Thread.Sleep(250);
        //    }

        //}
        

    }
}
